#! /bin/sh

#---------------------------------------------------------------------
#                           chicken and egg                           
#---------------------------------------------------------------------

test -f "${FW_ROOT}/share/fw/sh/fw-find.sh" && fws="${FW_ROOT}/share/fw/sh/fw-find.sh"
test -f "fw/sh/fw-find.sh" && fws="fw/sh/fw-find.sh"
test -f "fw.local/sh/fw-find.sh" && fws="fw.local/sh/fw-find.sh"
test ! -z "$fws" || {
  echo "package/deb/make-package: fatal: can't locate fw-find.sh" 1>&2
  exit 1
}

. "$fws"

#---------------------------------------------------------------------
#                              routines                               
#---------------------------------------------------------------------

fw_source "package/deb/make-package" "sh/fatal.sh"
fw_source "package/deb/make-package" "sh/fw-exec.sh"
fw_source "package/deb/make-package" "sh/parse-args.sh"
fw_source "package/deb/make-package" "sh/validate-args.sh"

# TODO: this seems somewhat C/C++ specific ... can we move this
# into those templates somehow?
# IDEA: 1. expose the "search" hook as a package method
#       2. make an (optional) add-automatic-dependencies template hook

get_automatic_dependencies () \
  {
    local _libs;
    local _depends;

    _libs=`
      find "$destdir" -perm +111 -type f | xargs "$ldd" $ldd_args 2>/dev/null |   \
      perl -lne 'm%=> (/.*?) \(0x% && do { 
                    $x = $1; 
                    $x =~ s/(\s)/\134$1/g; 
                    print $x; 
                 };
                 m%(/.*?) \(comp% && do {
                    $x = $1; 
                    $x =~ s/(\s)/\134$1/g; 
                    print $x; 
                 }' | \
      grep -v "$FW_PACKAGE_NAME"`

    _depends=`
      (
        dpkg --search $_libs 2>/dev/null |                              \
        perl -lne 'm%^(.*?): /% && ! $seen{$1}++ && do { 
                    print STDERR "package/deb/make-package: warning: adding inferred dependency $1"; 
                    print $1
                   }'
        perl -e 'print join "\n", split /,/, $ARGV[0]' "$FW_PACKAGE_DEPENDS"
      ) |                                                               \
      perl -ne 'chomp; 
                next if $seen{$_}++; 
                print ", " unless ! $first++;
                print "$_";'`

    eval $1=\"\$_depends\"
  }

make_control_files () \
  {
    local description
    local okmd5

    mkdir "$destdir"/DEBIAN || fatal "package/deb/make-package"
    chmod 755 "$destdir"/DEBIAN || fatal "package/deb/make-package"

    description=`echo "$FW_PACKAGE_DESCRIPTION" | perl -ne 's/^$/./; print " $_";'`

    priority=${FW_PACKAGE_PRIORITY:-"Optional"}

    get_automatic_dependencies depends

    if test -n "$depends"
      then
        rangedepends=`fw_exec package/deb/dependency-range "$depends"`
      else
        rangedepends=""
      fi

    cat <<EOD > "$destdir"/DEBIAN/control
Package: $package
Version: $version
Architecture: $arch
Maintainer: $FW_PACKAGE_MAINTAINER
Description: $FW_PACKAGE_SHORT_DESCRIPTION
$description
Depends: $rangedepends
Conflicts: $FW_PACKAGE_CONFLICTS
Provides: $FW_PACKAGE_PROVIDES
Replaces: $FW_PACKAGE_REPLACES
Suggests: $FW_PACKAGE_SUGGESTS
Priority: $priority

EOD
    hookdir="${libexecdir}/fw/$FW_PACKAGE_NAME-$FW_PACKAGE_VERSION"

    for x in pre-install post-install pre-remove post-remove
      do
        target=`echo "$x" | perl -pe 's%^post-%post%;
                                      s%^pre-%pre%; 
                                      s%install%inst%;
                                      s%remove%rm%;'`
        test ! -f "${destdir}/${hookdir}/$x" ||                            \
        cp -f "${destdir}/${hookdir}/$x" "${destdir}/DEBIAN/${target}" ||  \
        fatal "package/deb/make-package"
      done

    for x in start stop
      do
        if test "$x" = "start"
          then
            okmd5=7a8768f94ba14a74361731a2c4bf9d20
          else
            okmd5=71e59480baed6df5ce42e42f69d5a077
          fi

        test -f "${destdir}/${hookdir}/$x" &&                           \
        test "`md5sum "${destdir}/${hookdir}/$x" | cut -f1 -d' '`" != $okmd5 && \
        echo "package/deb/make-package: warning: $x hook not supported" 1>&2
      done
  }

#---------------------------------------------------------------------
#                                main                                 
#---------------------------------------------------------------------

parse_args "package/deb/make-package" "$@"

validate_args "package/deb/make-package" "destdir libexecdir ldd outdir release template" "template"

which dpkg >/dev/null 2>/dev/null || {
  echo "package/deb/make-package: error: dpkg not installed" 1>&2
  fatal "package/deb/make-package"
}

eval `fw_exec "template/$template/load-config"`

package=`fw-exec package/deb/canonicalize-package "${FW_PACKAGE_NAME}"` || fatal package/deb/make-package
version=`fw-exec package/deb/canonicalize-version "${FW_PACKAGE_VERSION}"` || fatal package/deb/make-package

if test "$FW_PACKAGE_ARCHITECTURE_DEPENDENT" = "1"
  then
    arch=`dpkg --print-architecture`
  else
    arch="all"
  fi

test "$release" = yes || version="${version}-TEST1"

make_control_files

if which fakeroot >/dev/null 2>/dev/null
  then
    file="`perl -e '($_) = @ARGV; s%/[^/]+/?$%/fakeroot.dat%; print $_;' \"$destdir\"`"
    fakeroot -i "$file" -s "$file" -- \
      dpkg --build "$destdir" "${outdir}/${package}_${version}_${arch}.deb"
  else
    dpkg --build "$destdir" "${outdir}/${package}_${version}_${arch}.deb"
  fi
